package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"news-mgmt-sys/cache"
	"news-mgmt-sys/model"
	"strconv"
	"time"
)

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var news model.News
	redis_key := "news_list_" + strconv.Itoa(id)
	DataRedis, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if DataRedis == "" {
		model.DB.Where("id=?", id).Find(&news)
		joinData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, joinData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(DataRedis), &news)
	}
	c.JSON(200, gin.H{
		"coed": 200,
		"msg":  "查询成功",
		"data": news,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var news []model.News
	var total int64
	redis_key := "news_list_" + strconv.Itoa(page)
	DataRedis, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if DataRedis == "" {
		model.DB.Offset(offset).Limit(size).Find(&news)
		joinData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, redis_key, joinData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(DataRedis), &news)
	}
	model.DB.Model(&news).Count(&total)
	c.JSON(200, gin.H{
		"coed":  200,
		"msg":   "查询成功",
		"data":  news,
		"total": total,
	})
	return
}

func Upload(c *gin.Context) {
	file, _ := c.FormFile("file")
	if file == nil {
		c.JSON(200, gin.H{
			"coed": 500,
			"msg":  "上传文件不能为空",
		})
		return
	}
	filename := uuid.NewString() + ".png"
	path := "static/img/" + filename
	err := c.SaveUploadedFile(file, "./"+path)
	if err != nil {
		c.JSON(200, gin.H{
			"coed": 500,
			"msg":  "文件上传失败",
		})
		return
	}
	URL := "http://127.0.0.1:8000/" + path
	c.JSON(200, gin.H{
		"coed": 200,
		"msg":  "文件上传成功",
		"URL":  URL,
	})
	return
}
